import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/login'
import Layout from '@/views/layout'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'

// 引用vuex的仓库
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      // 配嵌套子路由
      // 1. 完整写法 '/dashboard'
      // 2. 相对路径写法：'dashboard'，会自动拼接上前面的父路由路径
      children: [
        { path: '/dashboard', component: Dashboard },
        { path: '/article', component: Article }
      ]
    }

  ]
})

// 路由前置守卫
// 白名单数组，只有登录页
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 1. 如果有token，直接放行
  if (token) {
    // 1.1. 有token时访问注册登录页，跳转到首页
    if (whiteList.includes(to.path)) {
      next('/')
    }
    next()

    // 2. 如果没有token，但访问路径在白名单中，直接放行
  } else if (whiteList.includes(to.path)) {
    next()

    // 3. 否则跳转到登录页
  } else {
    next('/login')
  }
})

export default router
